package search.doublepointer;

/**
 * https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
 * 求两数之和问题
 */
public class TwoSum {

    public static void main(String[] args) {

        int[] nums ={1,3,4,6,7,8,12,15,19};
        int[] ret =new TwoSum().twoSum(nums,27);
        for(int i:ret) {
            System.out.println(i);
        }
    }
    /**
     * 两数求和 ，要求时间复杂度为 0（n)
     * @param nums 有序集合
     * @param val 目标
     * @return 结果 (注意返回的不是数组索引) --> 索引 +1
     */
    public int[] twoSum(int[] nums, int val) {

        //存放结果
        int[] result = {-1, -1};
        if (nums == null || nums.length == 0) {
            return result;
        }
        int start = 0;
        int end = nums.length - 1;
        while (start < end) {
            if (nums[start] + nums[end] < val) {
                start++;
            } else if (nums[start] + nums[end] > val) {
                end--;
            } else {
                result[0] = start + 1;
                result[1] = end + 1;
                break;
            }
        }
        return result;
    }
}
